import json

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.utils.timezone import localtime
from rest_framework import status
from django.core.exceptions import ValidationError
from apps.users.models import Classes, Student, Question, PK


# Create your views here.
#班级信息
class HomeView(APIView):
    def get(self, request):
        classes = Classes.objects.all().count()
        students = Student.objects.all().count()
        questions = Question.objects.all().count()
        return Response({'message': 'ok', 'class_num': classes,
                         'student_num': students,
                         'question_num': questions})


#pk历史
class HistoryView(APIView):
    def get(self, request):
        id = request.GET.get('type')
        history = []
        if id == '0':
            history = PK.objects.all()
        elif id == '1':
            history = PK.objects.filter(type=1).all()
        elif id == '2':
            history = PK.objects.filter(type=2).all()
        data = []
        for i in history:

            data.append({
                'pk_id': i.id,
                'class': i.PK_name,
                'time_pk': str(i.start_date),
                'win': i.win
            })
        return Response({'errmsg': 'OK', 'data': data})


# 题库管理
class QuestionHouse(APIView):
    def post(self, request):
        try:
            data = request.data
            question_name = data.get('title')
            if not question_name:
                raise ValidationError("Title field is required.")
            ask = data.get('answer')
            if not ask:
                raise ValidationError("Ask field is required.")
            state = data.get('type')
            Question.objects.create(
                question_name=question_name,
                ask=ask,
                state=state
            )
            return Response({"message": "Question added successfully."}, status=status.HTTP_201_CREATED)
        except ValidationError as e:
            return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as ex:
            return Response({"error": f"An unexpected error occurred: {str(ex)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)